import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Table, Divider, Tag, Card, Switch, Popover, Radio, Form, Button, Popconfirm, message, Input, Icon } from 'antd';
import Highlighter from 'react-highlight-words';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;


@connect(({ user }) => ({
  userList: user.userList,
}))
@Form.create()
class UserManage extends PageHeaderWrapper {
  state = {
    searchText: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/getUserList',
    })
  }

  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys, selectedKeys, confirm, clearFilters,
    }) => (
        <div style={{ padding: 8 }}>
          <Input
            ref={node => { this.searchInput = node; }}
            placeholder={`Search ${dataIndex}`}
            value={selectedKeys[0]}
            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
            onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
            style={{ width: 188, marginBottom: 8, display: 'block' }}
          />
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm)}
            icon="search"
            size="small"
            style={{ width: 90, marginRight: 8 }}
          >
            Search
          </Button>
          <Button
            onClick={() => this.handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            Reset
          </Button>
        </div>
      ),
    filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) => record[dataIndex]!==null ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) : null,
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: (text) => (
      text === null ? null :
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  })

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  }

  handleReset = (clearFilters) => {
    clearFilters();
    this.setState({ searchText: '' });
  }

  handleSubmit = (id) => {
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        console.log("form", values);
        dispatch({
          type: 'user/setNewRole',
          payload: {
            id: id,
            newRole: values.role,
          },
          // callback: (res) => {
          //   if (res) {
          //     this.setState({
          //     });
          //   }
          // }
        })
      }
    });
  }

  onChange = (checked, id) => {
    console.log(`switch to ${checked}`);
    const { dispatch } = this.props;
    dispatch({
      type: 'user/setUserStatus',
      payload: {
        id: id,
        status: checked === true ? 1 : 0,
      },
      // callback: (res) => {
      //   if (res) {
      //     this.setState({
      //     });
      //   }
      // }
    })
  }

  confirm = (e) => {
    console.log(e);
    message.success('删除成功');
  }

  cancel = (e) => {
    console.log(e);
  }

  render() {
    const { userList } = this.props;
    console.log(userList)
    const columns = [{
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      ...this.getColumnSearchProps('username'),
    }, {
      title: '学号',
      dataIndex: 'code',
      key: 'code',
      ...this.getColumnSearchProps('code'),

    }, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      ...this.getColumnSearchProps('name'),

    }, {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: text => (
        <span>
          {text === 1 ? <Tag color="blue">男</Tag> : text === 2 ? <Tag color="blue">女</Tag> : <Tag>未知</Tag>}
        </span>
      ),
    }, {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      ...this.getColumnSearchProps('phone'),
    }, {
      title: '角色',
      key: 'roles',
      dataIndex: 'roles',
      render: (roles, record) => (
        <span>
          {roles.map(role => {
            let color = 'volcano';
            if (role === 'admin') {
              color = 'red';
            } else if (role === 'user') {
              color = 'green';
            }
            return (
              <Popover
                key={role}
                content={
                  <Form>
                    <FormItem>
                      {this.props.form.getFieldDecorator('role', {
                        initialValue: role
                      })(
                        <RadioGroup>
                          <Radio value={'user'}>User</Radio>
                          <Radio value={'teacher'}>Teacher</Radio>
                          <Radio value={'admin'}>Admin</Radio>
                        </RadioGroup>
                      )}
                    </FormItem>
                    <FormItem>
                      <Button type="primary" onClick={() => this.handleSubmit(record.id)}>确认</Button>
                    </FormItem>
                  </Form>
                }
                title="选择角色"
                trigger="click"
              >
                <Tag color={color}>{role.toUpperCase()}</Tag>
              </Popover>
            );
          })}
        </span>
      ),
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => (
        <span>
          <Switch checkedChildren="开" unCheckedChildren="关" defaultChecked={text === 1 ? true : false} onChange={(checked) => this.onChange(checked, record.id)} />
        </span>
      )
    },
      // {
      //   title: 'Action',
      //   key: 'action',
      //   render: (text, record) => (
      //     <span>
      //       {/* <a href="javascript:;">Invite {record.name}</a> */}
      //       <Divider type="vertical" />
      //       <Popconfirm title="Are you sure delete this user?" onConfirm={this.confirm} onCancel={this.cancel} okText="Yes" cancelText="No">
      //         <a href="javascript:;">Delete</a>
      //       </Popconfirm>

      //     </span>
      //   ),
      // }
    ];

    return (
      <PageHeaderWrapper>
        <Card>
          <Table columns={columns} dataSource={userList} rowKey={record => record.id} />
        </Card>

      </PageHeaderWrapper>
    )
  }
}
export default UserManage;